import 'package:moonmate/services/shared_preferences_service.dart';

class RemainingDaysService {
  final SharedPreferencesService _prefsService;

  RemainingDaysService() : _prefsService = SharedPreferencesService() {
    _prefsService.initialize();
  }

  Future<Map<String, dynamic>> getRemainingDays(int userId) async {
    try {
      // 获取用户的目标日期
      final userProfile = _prefsService.getObject(SharedPreferencesService.keyUser);
      if (userProfile == null || userProfile['target_date'] == null) {
        return {
          'days_remaining': null,
          'target_date': null,
          'percentage_complete': 0,
          'message': '请设置目标日期',
        };
      }

      // 计算剩余天数
      final now = DateTime.now();
      final targetDate = DateTime.parse(userProfile['target_date']);
      final daysRemaining = targetDate.difference(now).inDays;

      // 计算完成百分比（假设总天数为365天）
      const totalDays = 365;
      final elapsedDays = totalDays - daysRemaining;
      final percentageComplete = (elapsedDays / totalDays * 100).clamp(0, 100);

      // 获取用户的叶酸摄入记录
      final folicAcidRecords = _prefsService.getObjectList(SharedPreferencesService.keyFolicAcid)
          .where((record) => record['user_id'] == userId).toList();

      // 计算叶酸依从率
      double folicAcidComplianceRate = 0.0;
      if (folicAcidRecords.isNotEmpty) {
        final folicAcidTakenRecords = folicAcidRecords.where((record) => record['taken'] == true || record['taken'] == 1).length;
        folicAcidComplianceRate = (folicAcidTakenRecords / folicAcidRecords.length) * 100;
      }

      return {
        'days_remaining': daysRemaining,
        'target_date': targetDate,
        'percentage_complete': percentageComplete,
        'folic_acid_compliance_rate': folicAcidComplianceRate,
        'progress_records_count': folicAcidRecords.length,
        'message': daysRemaining >= 0 ? '继续加油！' : '目标日期已过，继续保持良好习惯',
      };
    } catch (e) {
      // 计算剩余天数失败
      return {
        'days_remaining': null,
        'target_date': null,
        'percentage_complete': 0,
        'message': '计算失败',
      };
    }
  }

  Future<bool> updateProgress(int userId, Map<String, dynamic> progressData) async {
    try {
      // 确保包含用户ID和日期
      final completeData = {
        'id': DateTime.now().millisecondsSinceEpoch.toString(),
        ...progressData,
        'user_id': userId,
        'date': progressData['date'] ?? DateTime.now().toIso8601String(),
        'created_at': DateTime.now().toIso8601String(),
      };

      return await _prefsService.addObjectToList(SharedPreferencesService.keyProgressRecords, completeData);
    } catch (e) {
      // 更新进度失败
      return false;
    }
  }

  Future<List<Map<String, dynamic>>> getProgressHistory(int userId, {int limit = 30}) async {
    try {
      final records = _prefsService.getObjectList(SharedPreferencesService.keyProgressRecords)
          .where((record) => record['user_id'] == userId)
          .toList();
      
      // 按日期排序（降序）
      records.sort((a, b) {
        final dateA = DateTime.parse(a['date'] as String);
        final dateB = DateTime.parse(b['date'] as String);
        return dateB.compareTo(dateA);
      });
      
      // 返回指定数量的记录
      return records.take(limit).toList();
    } catch (e) {
      // 获取进度历史失败
      return [];
    }
  }
}